<?php


namespace app\common\business;


class GoodsSku
{
    public $goodsModel = null;

    public function __construct() {
        //初始化模型对象
        $this->goodsSkuModel = new \app\common\model\mysql\GoodsSku();
    }

    public function save($data) {
        if (!$data['goods_id']) {
            return false;
        }
        try {
            $this->goodsSkuModel->save($data);
            return $this->goodsSkuModel->id;
        }catch (\Exception $e) {
            //echo $e->getMessage();exit;
            // 记录日志
            return false;
        }
    }

    public function saveAll($data) {
        if (!$data['skus']) {
            return false;
        }
        $insertData = [];
        foreach ($data['skus'] as $value) {
            $insertData[] = [
                "goods_id" => $data['goods_id'],
                "specs_value_ids" => $value['propvalnames']['propvalids'],
                "price" => $value['propvalnames']['skuSellPrice'],
                "cost_price" => $value['propvalnames']['skuMarketPrice'],
                "stock" => $value['propvalnames']['skuStock'],
            ];
        }
        try {
            $result = $this->goodsSkuModel->saveAll($insertData);
            return $result->toArray();
        }catch (\Exception $e) {
            ///echo $e->getMessage();exit;
            // 记录日志
            return false;
        }
        return true;
    }

    public function getNormalSkuAndGoods($skuId) {
        try {
            $result = $this->goodsSkuModel->with("goods")->find($skuId);
        }catch(\Exception $e) {
            return [];
        }
        if(!$result) {
            return [];
        }
        $result = $result->toArray();
        if($result['status'] != 1) {
            return [];
        }
        return $result;
    }

    public function getSkusByGoodsId($goodsId = 0) {
        if(!$goodsId) {
            return [];
        }
        try {
            $skus = $this->goodsSkuModel->getNormalByGoodsId($goodsId);
        }catch (\Exception $e) {
            return [];
        }
        return $skus->toArray();
    }

    public function getNormalInIds($ids) {
        try {
            $result = $this->goodsSkuModel->getNormalInIds($ids);
        }catch (\Exception $e) {
            return [];
        }
        return $result->toArray();
    }

    public function updateStock($data) {
        foreach ($data as $value) {
            $this->goodsSkuModel->decStock($value['sku_id'], $value['num']);
        }
        return true;
    }
    public function addStock($data) {
        foreach ($data as $value) {
            $this->goodsSkuModel->incStock($value['sku_id'], $value['num']);
        }
        return true;
    }
}